<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <a-form size="small" :model="pageData.queryData" layout="inline">
          <a-form-item :label-col-flex="pageData.labelColFlex1" label="批色配方单号" label-col-flex="80px" :style="{width:'330px'}">
            <a-input
              @press-enter="selectHandler"
              class="bacClass"
              v-model="pageData.queryData.batchcolorFormulaCode"
              allow-clear
            />
          </a-form-item>
          <a-form-item :label-col-flex="pageData.labelColFlex1" label="日期" label-col-flex="80px" :style="{width:'330px'}">
            <a-range-picker  popup-container="html" 
              class="bacClass"
              v-model="pageData.queryData.createTimeArr"
            />
          </a-form-item>
        </a-form>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <Toolbar
          :items="['查询', '审核', '新增', '删除']"
          @audit="setAudit"
          @add="addHandler"
          @del="deleteHandler"
          @select="selectHandler"
        >
        </Toolbar>
      </div>
    </template>
    <template #pageTabel>
      <AgGridVuesCopys
        :rowHeight="33"
        :headerHeight="33"
        rowSelection="multiple"
        @grid-ready="gridReady"
        style="height: 100%"
        :defaultColDef="defaultColDef"
        class="ag-theme-alpine"
        :rowData="table.dataList"
        :columnDefs="tc"
        :localeText="localeText1"
        :suppressRowClickSelection="true"
      ></AgGridVuesCopys>
    </template>

    <paginationCopys
      :page-size="pagination.pageSize"
      :current="pagination.page"
      :total="pagination.total"
      show-total
      show-jumper
      show-page-size
      @change="nextDoRefreshPage"
      @page-size-change="nextDoRefreshSize"
      style="justify-content: center"
    />

    <a-drawer
      placement="bottom"
      :drawer-style="{ zIndex: 9999 }"
      :mask-closable="false"
      height="90%"
      :visible="pageData.showAdd"
      unmountOnClose
      @ok="sideOk"
      @cancel="pageData.showAdd = false"
      cancel-text="关闭"
      ok-text="保存"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" :model="dataForm" layout="horizontal">
          <a-row class="grid-demo" :gutter="24">
            <a-col :span="6">
              <a-form-item
                label="部门"
                field="departmentId"
                :label-col-flex="pageData.labelColFlex"
                :validate-trigger="['change', 'blur']"
                :rules="[{ required: true, message: '部门必填' }]"
              >
                <a-cascader
                  v-model="dataForm.departmentId"
                  :options="pageData.departmentTree"
                  ref="casOb3"
                  class="bacClass"
                  :check-strictly="true"
                  popup-container="html"
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item
                label="部门员工"
                field="departmentPerson"
                :label-col-flex="pageData.labelColFlex"
                :validate-trigger="['change', 'blur']"
                :rules="[{ required: true, message: '部门员工必填' }]"
              >
                <a-select popup-container="html" 
                  v-model="dataForm.departmentPerson"
                  class="bacClass"
                  placeholder="请选择部门员工"
                  allow-clear
                >
                  <a-option>张三</a-option>
                  <a-option>李四</a-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row class="grid-demo" :gutter="24">
            <el-table
              :data="[{}]"
              style="width: 100%"
              :header-cell-style="{ color: '#696969', background: '#f5f7fa' }"
              tooltip-effect="dark"
            >
              <el-table-column prop="" label="物料编号">
                <a-input v-model="dataForm.batchcolorFormulaDetail[0].materialCode" />
              </el-table-column>
              <el-table-column prop="" label="物料名称">
                <a-input v-model="dataForm.batchcolorFormulaDetail[0].materialName" />
              </el-table-column>
              <el-table-column prop="" label="用量">
                <a-input-number v-model="dataForm.batchcolorFormulaDetail[0].dosage" />
              </el-table-column>
              <el-table-column prop="" label="单位">
                <a-input v-model="dataForm.batchcolorFormulaDetail[0].unit" />
              </el-table-column>
              <el-table-column prop="" label="化工仓库存数">
                <a-input-number v-model="dataForm.batchcolorFormulaDetail[0].warehouseNum" />
              </el-table-column>
              <el-table-column prop="" label="用途">
                <a-input v-model="dataForm.batchcolorFormulaDetail[0].purpose" />
              </el-table-column>
              <el-table-column prop="" label="备注">
                <a-input v-model="dataForm.batchcolorFormulaDetail[0].remark" />
              </el-table-column>
            </el-table>
          </a-row>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
  import { post, get } from '@/api/http'
  import { useTable, usePagination, useTableColumn } from '@/hooks/table'

  import { ref, reactive, onMounted } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import 'ag-grid-community/styles/ag-grid.css'
  import 'ag-grid-community/styles/ag-theme-alpine.css'
  import { localeText } from '@/api/aggridZw'
  
  import { slicing } from '@/utils/caseFrimAndSecRig'

  interface paramData {
    id: any
    department: string | undefined //部门
    departmentPerson: string | undefined //部门员
    batchcolorFormulaDetail: any
  }

  export default {
    //批色开方
    name: 'BatchColorFormula',
    setup() {
      //隐藏显示头部
      const headerShow = ref<boolean>(true)
      const pageData = reactive<{
        showAdd: boolean
        sideTitle: string
        dropDownData: any
        pageLoading: boolean
        theight: number
        rHeight: number | undefined
        labelColFlex: string
        queryData: any
        labelColFlex1: string
        departmentTree: any
      }>({
        showAdd: false,
        sideTitle: '新增批色开方',
        dropDownData: '',
        pageLoading: false,
        theight: 0,
        rHeight: 0,
        labelColFlex: '120px',
        queryData: {
          batchcolorFormulaCode: '',
          createTimeArr: [],
          beginDate: '',
          endDate: '',
        },
        labelColFlex1: '100px',
        departmentTree: [],
      })
      const dataForm = reactive<any>({
        id: null,
        department: '', //部门
        departmentId: '',
        departmentPerson: '', //部门员
        batchcolorFormulaDetail: [],
      })
      //查询列表
      onMounted(() => {
        selectHandler()
      })

      //切换分页
      const nextDoRefreshPage = (val: any) => {
        pagination.page = val
        doRefresh()
      }
      const nextDoRefreshSize = (val: any) => {
        pagination.pageSize = val
        doRefresh()
      }
      const pagination = usePagination(doRefresh)
      const table = useTable()
      function doRefresh() {
        pageData.pageLoading = true
        pageData.queryData.page = pagination.page
        pageData.queryData.size = pagination.pageSize
        post({
          url: 'dwQms/BatchcolorFormula/getPage',
          data: pageData.queryData,
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              table.handleSuccess(data.list)
              pagination.setTotalSize(data.total)
              gridOption.value.setRowData(data.list)
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
      }
      //查询
      const selectHandler = () => {
        pagination.page = 1
        doRefresh()
      }
      //------新增、修改页面开始------
      const addHandler = () => {
        getBmGroup()
        for (var key in dataForm) {
          if (key === 'id') {
            dataForm[key] = null
          } else if (key === 'batchcolorFormulaDetail') {
            dataForm[key] = [
              {
                materialCode: '', //物料编号
                materialName: '', //物料名称
                dosage: '', //用量
                unit: '', //单位
                warehouseNum: '', //化工仓库存数
                purpose: '', //用途
                remark: '', //备注
              },
            ]
          } else {
            dataForm[key] = ''
          }
        }
        pageData.showAdd = true
        pageData.sideTitle = '新增批色开方'
      }
      const editHandler = (record: paramData) => {
        dataForm.batchcolorFormulaDetail = [
          {
            materialCode: '', //物料编号
            materialName: '', //物料名称
            dosage: '', //用量
            unit: '', //单位
            warehouseNum: '', //化工仓库存数
            purpose: '', //用途
            remark: '', //备注
          },
        ]
        getBmGroup()
        for (var key in record) {
          dataForm[key] = record[key]
        }
        post({
          url: 'dwQms/BatchcolorFormulaDetail/getList',
          data: {
            batchcolorFormulaId: record.id,
          },
        }).then(({ data, code }: any) => {
          if (code === 200) {
            dataForm.batchcolorFormulaDetail = data
            if (data[0].warehouseNum) {
              dataForm.batchcolorFormulaDetail[0].warehouseNum = Number(data[0].warehouseNum)
            }
          }
        })
        pageData.sideTitle = '修改批色开方'
        pageData.showAdd = true
      }

      const formRef = ref<FormInstance>()
      const casOb3 = ref<any>(null)
      watch(
        () => dataForm.departmentId,
        (newVal) => {
          nextTick(() => {
            dataForm.department = casOb3.value.selectViewValue[0].label
          })
        }
      )
      const sideOk = () => {
        formRef.value?.validate().then((err) => {
          if (!err) {
            if (pageData.sideTitle === '新增批色开方') {
              post({
                url: 'dwQms/BatchcolorFormula/insertList',
                data: dataForm,
              }).then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()

                  pageData.showAdd = false

                  Message.success({
                    content: '新增成功',
                    duration: 5000,
                  })
                  selectHandler()
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              })
            } else {
              post({
                url: 'dwQms/BatchcolorFormula/updateList',
                data: dataForm,
              }).then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  pageData.showAdd = false

                  Message.success({
                    content: '修改成功',
                    duration: 5000,
                  })
                  selectHandler()
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              })
            }
          }
        })
      }
      //------新增、修改页面结束------
      //------删除方法开始------
      const deleteHandler = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          return
        }
        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          onOk() {
            post({
              url: 'dwQms/BatchcolorFormula/delete',
              data: gridOption.value.getSelectedRows().map((o: any) => {
                return o.id
              }),
            }).then(({ code, data }: any) => {
              if (code === 200) {
                Message.success({
                  content: '删除成功',
                  duration: 5000,
                })

                pagination.page = 1
                selectHandler()
              } else {
                Message.error({
                  content: '删除失败',
                  duration: 5000,
                })
              }
            })
          },
        })
      }
      //------删除方法结束------

      // 表格准备事件
      const tableColumns = useTableColumn([
        {
          title: '序号',
          key: 'id',
          dataIndex: 'id',
        },
        {
          title: '批色配方单号',
          key: 'batchcolorFormulaCode',
          dataIndex: 'batchcolorFormulaCode',
        },
        {
          title: '部门',
          key: 'department',
          dataIndex: 'department',
        },
        {
          title: '审核状态',
          key: 'auditState',
          dataIndex: 'auditState',
          cellRenderer: {
            template: `
        <el-text class="mx-1" v-if="states == 0">未审核</el-text>
        <el-text class="mx-1" v-if="states == 1">审核通过</el-text>
        <el-text class="mx-1" v-if="states == 2">审核不通过</el-text>
        <el-text class="mx-1" v-if="states == 3">已处理</el-text>
        `,
            setup(props: any) {
              return {
                states: props.params.data.auditState,
              }
            },
          },
        },
        {
          title: '审核人',
          key: 'auditName',
          dataIndex: 'auditName',
        },
        {
          title: '审核日期',
          key: 'auditTime',
          dataIndex: 'auditTime',
        },
        {
          title: '备注',
          key: 'remark',
          dataIndex: 'remark',
        },
        {
          title: '创建人',
          key: 'createName',
          dataIndex: 'createName',
        },
        {
          title: '创建时间',
          key: 'createTime',
          dataIndex: 'createTime',
        },
        {
          title: '操作',
          key: 'id',
          dataIndex: 'id',
          slotName: 'act',
          width: 150,
          fixed: 'right',
        },
      ])
      const gridOption = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
      }
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        // flex: 1
      }
      let tc: any[] = tableColumns.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          width: o.width,
          children: o.children,
          cellRenderer: o.cellRenderer,
        }
        if (o.slotName === 'act') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = o.fixed
          obj['cellRenderer'] = {
            template: `<el-button style="color:#165dff;" link @click="a">修改</el-button>`,
            setup(props: any) {
              const a = () => {
                editHandler(props.params.data)
              }
              return {
                a,
              }
            },
          }
        }
        return obj
      })
      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      tc = a.concat(tc)
      const localeText1: any = ref(localeText)

      // 获取部门列表
      const getBmGroup = () => {
        post({
          url: 'org/baCompany/getDepartmentTree?companyId=' + 12,
        }).then((result) => {
          if (result.code === 200) {
            pageData.departmentTree = result.data
          }
        })
      }
      const setAudit = () => {
        if (gridOption.value.getSelectedRows().length !== 1) {
          Message.error({
            content: '请只选择一条数据进行审核！',
            duration: 5000,
          })
          return
        }
        Modal.confirm({
          title: '系统提示',
          content: '确认审核选中的数据?',
          onOk() {
            var obj: any = {
              id: gridOption.value.getSelectedRows()[0].id,
              auditState: 1,
            }
            post({
              url: 'dwQms/BatchcolorFormula/setAudit',
              data: [obj],
            }).then(({ code, data }: any) => {
              if (code === 200) {
                Message.success({
                  content: '操作成功',
                  duration: 5000,
                })

                pagination.page = 1
                selectHandler()
              } else {
                Message.error({
                  content: '操作失败',
                  duration: 5000,
                })
              }
            })
          },
        })
      }

      return {
        deleteHandler,
        sideOk,
        formRef,
        dataForm,
        addHandler,
        pagination,
        table,
        pageData,
        editHandler,
        selectHandler,
        headerShow,
        nextDoRefreshPage,
        nextDoRefreshSize,
        defaultColDef,
        localeText1,
        tc,
        gridReady,
        gridOption,
        getBmGroup,
        setAudit,
        casOb3,
      }
    },
    components: { Toolbar,  },
  }
</script>
<style scoped lang="less">
  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }
  :deep(.arco-picker input){
    padding-left: 0 !important;
}
:deep(.arco-picker){
    padding-left: 0 !important;
}
:deep(.arco-picker-separator){
    padding: 0 !important;
}
</style>
